package admin

import (
	"blogs/utils"
	beego "github.com/beego/beego/v2/server/web"
	"os"
	"path"
	"strconv"
)

// Operations about object
type ImgUploadController struct {
	beego.Controller
}

// @Title Create
// @Description 上传图片
// @Success 200 {string} 图片
// @Failure 403 body is empty
// @router / [post]
func (o *ImgUploadController) Post() {
	f, h, err := o.GetFile("file")
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"msg":  "图片上传错误",
			"data": "图片上传错误",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	//关闭文件流
	defer f.Close()

	//3、获取后缀名 判断类型是否正确  .jpg .png .gif .jpeg
	extName := path.Ext(h.Filename)
	allowExtMap := map[string]bool{
		".jpg":  true,
		".png":  true,
		".gif":  true,
		".jpeg": true,
	}
	if _, ok := allowExtMap[extName]; !ok {
		o.Data["json"] = map[string]interface{}{
			"msg":  "图片后缀名不合法",
			"data": "图片后缀名不合法",
			"code": false,
		}
		o.ServeJSON()

		return
	}
	//创建图片保存目录  static/upload/20200623
	day := utils.GetDay()
	dir := "static/upload/" + day

	if err := os.MkdirAll(dir, 0666); err != nil {

		o.Data["json"] = map[string]interface{}{
			"msg":  "上传失败",
			"data": "上传失败",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	//生成文件名称   144325235235.png
	fileUnixName := strconv.FormatInt(utils.GetUnixNano(), 10)
	//static/upload/20200623/144325235235.png
	saveDir := path.Join(dir, fileUnixName+extName)
	//保存图片
	o.SaveToFile("flie", saveDir)

	o.Data["json"] = map[string]interface{}{
		"msg":  "上传成功",
		"data": saveDir,
		"code": false,
	}
	o.ServeJSON()

}
